package mylibrary.security;

import java.security.MessageDigest;
import java.util.Random;

import org.apache.commons.codec.binary.Hex;

public class MD5 {

	public static void main(String[] args) throws Exception {
	
		//System.out.println(MD5("gaoshuai"));
		System.out.println(MD5WithSalt("gaoshuai"));
		
	}
	
	
	
	public static String MD5(String s) throws Exception {
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		//messageDigest.reset();
		messageDigest.update(s.getBytes("UTF-8"));
		
		byte[] resultByte = messageDigest.digest();
		String result = new String(Hex.encodeHex(resultByte));
		
		return result;
	}
	
	public static String MD5WithSalt(String s) throws Exception {
		
		Random rand = new Random();
		
		byte[] salt = new byte[12];
		rand.nextBytes(salt);
		
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		messageDigest.update(salt);
		messageDigest.update(s.getBytes("UTF-8"));
		
		byte[] resultByte = messageDigest.digest();
		String result = new String(Hex.encodeHex(resultByte));
		
		return result;
	}
}

